/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="container-main">
    <div :style="{'transform': `scale(${shrink})`, 'transform-origin': 'left top', 'height': '100%'}">
      <div class="tuxingjiemian" v-show="curHomePage === 'Graphical' || curHomePage === 'Channelization'" :class="{'minifont': curBodyWidth <= 650}">
        <div class="tuxing-left" :class="{'changeWidth': graphicMode}" ref="tuxingLeft">
          <intersection-base-map
            ref="intersectionMap"
            :stateName="stateName"
            :crossStatusData="crossStatusData"
            :agentId="agentId"
            :roadDirection="roadDirection" />
          <div class="pattern-status" v-if="!graphicMode && crossStatusData.control !== 1 && crossStatusData.control !== 2 && crossStatusData.control !== 3">
            <div class="pattern-name cross-mess">{{$t('edge.overview.patternstate')}}</div>
            <div class="pattern-message">({{$t('edge.overview.cycle')}}: {{controlData.cycle}}  {{$t('edge.overview.patternoffset')}}: {{controlData.patternoffset}} {{$t('edge.overview.coordinationtime')}}: {{controlData.offset}})</div>
              <span class="pattern-explain"><el-checkbox v-model="checked">{{$t('edge.pattern.overLap')}}</el-checkbox></span>
          <!-- 没ring数据显示方案图 -->
          <pattern-list
          v-if="
            (controlData &&
              !controlData.rings &&
              contrloType === 'ring' &&
              !controlData.syncTime) ||
              (controlData && !controlData.rings && contrloType === 'ring')
          "
          :showBarrier="true"
          :controlPhase ="controlData"
          :contrloType="contrloType"
          :syncTime="controlData.syncTime"
          :patternStatusList="patterData ? patterData.rings : []"
          :cycles="patterData ? patterData.cycle : 0"
          :isPhase="false"
          :phaseList="phaseList"
        >
        </pattern-list>
            <!-- 1049没ring数据显示阶段图 -->
            <pattern-list
            v-else-if="controlData && !controlData.rings && contrloType === 'stage'"
            ref="boardCard"
            :stagesChange="patterData ? patterData.stagesList : []"
            :contrloType="contrloType"
            :controlData="controlData"
            :cycles="patterData ? patterData.cycle : 0"
            :syncTime="controlData.syncTime"
            :localPatternList="allPatternList"
            :showBarrier="true"
            :isPhase="false"
            :phaseList="phaseList"
          >
          </pattern-list>
          <pattern-list
            v-else
            ref="boardCard"
            :cycle="crossStatusData ? crossStatusData.cycle : 0"
            :syncTime="crossStatusData ? crossStatusData.syncTime : 0"
            :controlData="controlData"
            :contrloType="contrloType"
            :localPatternList="allPatternList"
            :phaseList="phaseList"
            :showBarrier="true"
            :isPhase="false"
            :agentId="agentId"
          >
          </pattern-list>
            <!-- <over-lap
            v-if="this.contrloType === 'ring'"
            :checked="checked"
            :overlap="overlap"
            :stageList="stagesListOver"
            :cycle="overlapCycle"
            :controlData="controlData"
            >
            </over-lap> -->
          </div>
        </div>

        <div ref="tuxingRight" class="tuxing-right" >
          <scheme-config
            ref="rightpanel"
            :statusData="crossStatusData"
            :phaseList="phaseList"
            :agentName="agentName"
            :responseTime="responseTime"
            :agentId="agentId"
            :ip="ip"
            :platform="platform"
            :funcSort="FuncSort"
            :roadDirection="roadDirection"
            :isFromAtc="isfromatc" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import { getTscControl, queryDevice } from '../../../../api/control'
import { registerMessage, uploadSingleTscParam } from '../../../../api/param'
import { getIntersectionInfo } from '../../../../api/template'
import { setIframdevid } from '../../../../utils/auth.js'
import { getMessageByCode } from '../../../../utils/responseMessage'
import PhaseDataModel from 'openatc-components/package/kisscomps/components/IntersectionMap/crossDirection/utils.js'
import CrossDiagramMgr from 'openatc-components/src/EdgeMgr/controller/crossDiagramMgr'
export default {
  name: 'overview-new',
  components: {
  },
  props: {
    AgentId: {
      type: String,
      default: '0'
    }
  },
  data () {
    return {
      stateName: this.$t('openatccomponents.overview.offline'),
      controlData: {},
      checked: false,
      overlap: [],
      contrloType: '',
      narr: [],
      // patternList: [],
      // patternSelect: [], // 所有方案id
      // planPattern: {}, // 默认显示方案
      allPatternList: [], // 所有方案
      stagesListOver: [],
      sidewalkPhaseData: [],
      phaseControlTimer: null, // 定时器
      registerMessageTimer: null, // 延时器
      volumeControlTimer: null, // 流量定时器
      detectorStatusTimer: null, // 检测器定时器
      ParamsMode: new Map([[0, '自主控制'], [1, '本地手动'], [2, '平台控制'], [3, '配置软件控制'], [4, '遥控器控制'], [5, '黄闪器控制'], [6, '降级控制'], [7, '脚本控制'], [8, '算法控制']]),
      ParamsModeEn: new Map([[0, 'Autonomous Control'], [1, 'Local Manual'], [2, 'Platform Control'], [3, 'Configuration Software Control'], [4, 'Remote Control'], [5, 'Yellow Flasher Control'], [6, 'Degradation Control'], [7, 'Script Control'], [8, 'Algorithm Control']]),
      ParamsControl: new Map([[0, '多时段'], [1, '黄闪'], [2, '全红'], [3, '关灯'], [4, '步进'], [5, '定周期控制'], [6, '自适应'], [7, '协调感应控制'], [8, '方案选择控制'], [9, '方案生成'], [10, '无电缆控制'], [11, '有电缆控制'], [12, '行人过街控制'], [13, '方案恢复过渡'], [14, '相位驻留'], [15, '通道检测'], [16, '方向锁定'], [17, '韦伯斯特单点控制'], [18, '预留18'], [19, '感应式行人过街'], [20, '方案干预'], [100, '方案干预'], [21, '预留21'], [22, '相位锁定'], [23, '相位放行控制'], [24, '紧急控制'], [99, '设备维护']]),
      ParamsControlEn: new Map([[0, 'Multi Period'], [1, 'Yellow Flash Control'], [2, 'Red Control'], [3, 'Dark Control'], [4, 'Step'], [5, 'Fixed_Cycle Control'], [6, 'Free Control'], [7, 'Coordinated Induction Control'], [8, 'Pattern Selection Control'], [9, 'Adaptive Control'], [10, 'Wireless Control'], [11, 'Cable Control'], [12, 'Pedestrian Crossing Control'], [13, 'Pattern recovery'], [14, 'Phase dwell'], [15, 'Channel Detection'], [16, 'Direction lock'], [17, 'Webster Single Point Coordination'], [18, 'Reserving18'], [19, 'Inductive Pedestrian Crossing Control'], [20, 'Program Intervention'], [100, 'Program Intervention'], [21, 'Reserving21'], [22, 'Priority Control'], [23, 'Close Phase'], [24, 'Emergency Control'], [99, 'Device Mantenance']]),
      phaseType: new Map([[1, '红'], [2, '黄'], [3, '绿'], [4, '绿闪']]), // phaseType表示红，黄，绿
      phaseTypeEn: new Map([[1, 'Red'], [2, 'Yellow'], [3, 'Green'], [4, 'Greenclear']]), // phaseType表示红，黄，绿
      ip: '--',
      port: '--',
      protocol: '--',
      // devStatus: 1,
      mode: '2',
      agentId: '0',
      agentName: '',
      overlapCycle: 0,
      platform: undefined,
      crossStatusData: {}, // 路口状态数据
      detectorStatusData: {}, // 检测器状态数据（包括车辆检测器状态和行人检测器状态）
      reset: false,
      responseTime: 0,
      phaseList: [], // 当前相位集合
      intervalFlag: true,
      detIntervalFlag: true,
      shrink: 1,
      isResend: true,
      commonHeight: undefined, // 左右侧面板的高度值
      graphicMode: false
    }
  },
  computed: {
    // patternList () {
    //   return this.$store.state.globalParam.tscParam.patternList
    // },
    patterData () {
      return this.allPatternList.filter(item => {
        return item.id === this.controlData.patternid
      })[0]
    },
    ...mapGetters([
      'isfromatc'
    ]),
    ...mapState({
      curBodyWidth: state => state.globalParam.curBodyWidth,
      curBodyHeight: state => state.globalParam.curBodyHeight,
      FuncSort: state => state.globalParam.FuncSort,
      hideMenu: state => state.globalParam.hideMenu,
      curHomePage: state => state.globalParam.curHomePage,
      roadDirection: state => state.globalParam.roadDirection,
      curOpenatcAgentid: state => state.globalParam.curOpenatcAgentid,
      detectorList: state => state.globalParam.tscParam.detectorList,
      pedestrainDetectorList: state => state.globalParam.tscParam.pedestrainDetectorList
    })
  },
  watch: {
    AgentId: {
      handler: function (val, oldVal) {
        this.agentId = val
      },
      // 深度观察监听
      deep: true
    },
    // $route: {
    //   handler: function (val, oldVal) {
    //     if (val.query !== undefined) {
    //       if (this.$route.query.shrink) {
    //         this.shrink = Number(this.$route.query.shrink)
    //       }
    //       this.agentId = this.$route.query.agentid
    //       setIframdevid(this.agentId)
    //       this.getPlatform()
    //       this.getIntersectionInfo(this.agentId)
    //       this.$refs.rightpanel.getFaultById()
    //     }
    //   },
    //   // 深度观察监听
    //   deep: true
    // },
    phaseList: {
      handler: function (val, oldVal) {
        this.getPedPhasePos()
      },
      // 深度观察监听
      deep: true
    },
    curOpenatcAgentid: {
      handler: function (val) {
        // 平台设备切换时行人横道切换
        this.getPhase()
        this.initData()
      },
      deep: true
    }
  },
  created () {
    this.globalParamModel = this.$store.getters.globalParamModel
    this.PhaseDataModel = new PhaseDataModel()
    this.CrossDiagramMgr = new CrossDiagramMgr()
    // if (this.$route.query !== undefined && Object.keys(this.$route.query).length) {
    this.agentId = this.AgentId
    setIframdevid(this.agentId)
    this.registerMessage() // 注册消息
    this.getIntersectionInfo(this.agentId)
  },
  mounted () {
    this.getPlatform()
    if (this.$route.query.shrink) {
      this.shrink = Number(this.$route.query.shrink)
    }
    this.$nextTick(() => {
      this.$refs.intersectionMap.resetCrossDiagram()
    })
  },
  updated () {
    if (this.$refs.tuxingLeft.offsetHeight !== this.commonHeight) {
      // 根据左侧面板动态变化的高度，同步更新右侧面板高度
      this.commonHeight = this.$refs.tuxingLeft.offsetHeight
      this.$refs.tuxingRight.style.height = this.commonHeight + 'PX'
    }
  },
  methods: {
    getIntersectionInfo (agentid) {
      // 获取路口信息
      getIntersectionInfo(agentid).then(res => {
        if (sessionStorage.getItem('firstGet') !== 'false') {
          if (res.data.data.param.manualpanel === undefined) {
            res.data.data.param.manualpanel = {}
          }
          if (res.data.data.param.channellock === undefined) {
            res.data.data.param.channellock = []
          }
          if (res.data.data.param.channelList === undefined) {
            res.data.data.param.channelList = []
          }
          if (res.data.data.param.overlaplList === undefined) {
            res.data.data.param.overlaplList = []
          }
          if (res.data.data.param.detectorList === undefined) {
            res.data.data.param.detectorList = []
          }
          if (res.data.data.param.pedestrainDetectorList === undefined) {
            res.data.data.param.pedestrainDetectorList = []
          }
          if (res.data.data.param.preemptList === undefined) {
            res.data.data.param.preemptList = []
          }
          if (res.data.data.param.channelGreenConflictInfo === undefined) {
            res.data.data.param.channelGreenConflictInfo = []
          }
          if (res.data.data.param.singleoptim === undefined) {
            res.data.data.param.singleoptim = []
          }
        }
        this.allPatternList = res.data.data.param.patternList
        console.log(this.allPatternList)
        if (!this.allPatternList[0].contrloType && this.allPatternList[0].rings.length > 0) {
          this.contrloType = 'ring'
        } else if (!this.allPatternList[0].contrloType && this.allPatternList[0].rings.length === 0) {
          this.contrloType = 'stage'
        } else {
          this.contrloType = this.allPatternList[0].contrloType
        }
        this.overlap = res.data.data.param.overlaplList
        // this.phaseList = res.data.data.param.phaseList
        // this.patternPlan()
        // this.getCycle()
        // if (id) {
        //   this.patternList = res.data.data.param.patternList.filter(item => {
        //     return item.id === id
        //   })[0].rings
        // }
      })
    },
    getPedPhasePos () {
      // 行人相位信息
      this.sidewalkPhaseData = []
      this.phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
    },
    registerMessage () {
      registerMessage(this.agentId).then(data => {
        if (!data.data.success) {
          // this.devStatus = 2
          if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
            let success = data.data.data.content.success
            if (success !== 0) {
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.$message.error(this.$t(errormsg))
              return
            }
          }
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          if (this.isResend) {
            this.reSend()
          }
          return
        }
        // this.devStatus = 3
        this.clearPatternInterval() // 清除其他定时器
        this.clearVolumeInterval()
        this.phaseControlTimer = setInterval(() => {
          if (this.intervalFlag) {
            this.initData()
          }
        }, 1000)
        this.getPhase()
      })
    },
    reSend () { // 设备掉线重连机制
      // this.devStatus = 1
      this.clearRegisterMessageTimer()
      this.registerMessageTimer = setTimeout(() => {
        this.reconnectionDev()
      }, 5000)
    },
    clearPatternInterval () {
      if (this.phaseControlTimer !== null) {
        clearInterval(this.phaseControlTimer) // 清除定时器
        this.phaseControlTimer = null
      }
    },
    clearVolumeInterval () {
      if (this.volumeControlTimer !== null) {
        clearInterval(this.volumeControlTimer) // 清除流量定时器
        this.volumeControlTimer = null
      }
    },
    clearRegisterMessageTimer () {
      if (this.registerMessageTimer !== null) {
        clearTimeout(this.registerMessageTimer) // 清除延时器
        this.registerMessageTimer = null
      }
    },
    clearDetectorStatusTimer () {
      if (this.detectorStatusTimer !== null) {
        clearInterval(this.detectorStatusTimer) // 清除定时器
        this.detectorStatusTimer = null
      }
    },
    initData () {
      this.intervalFlag = false
      let startTime = new Date().getTime()
      getTscControl(this.agentId).then((data) => {
        let endTime = new Date().getTime()
        let diffTime = endTime - startTime
        this.responseTime = diffTime
        this.intervalFlag = true
        if (!data.data.success) {
          if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
            let success = data.data.data.content.success
            if (success !== 0) {
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.$message.error(this.$t(errormsg))
              return
            }
          }
          if (data.data.code === '4003') {
            // this.devStatus = 2
            this.clearPatternInterval() // 清除其他定时器
            this.clearVolumeInterval()
            this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
            if (this.isResend) {
              this.reSend()
            }
            return
          }
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          this.clearPatternInterval() // 清除其他定时器
          this.clearVolumeInterval()
          if (this.isResend) {
            this.reSend()
          }
          return
        }
        if (data.data.data.data) {
          this.crossStatusData = JSON.parse(JSON.stringify(data.data.data.data))
        } else {
          this.crossStatusData = {}
        }
        let TscData = JSON.parse(JSON.stringify(data.data.data.data))
        // this.handleStageData(TscData) // 处理阶段（驻留）stage数据
        this.controlData = this.handleGetData(TscData)
        console.log(this.controlData)
        this.checkStage(this.controlData)
      }).catch(error => {
        // this.$message.error(error)
        console.log(error)
      })
    },
    getControl (newList) { // 总揽实时数据
      let currentIds = ''
      let lastCurrentIds = ''
      this.stateList = [0]
      this.narr = []
      let overstagesList = []
      let phaseList = []
      for (let j = 0; j <= this.max; j++) { // 指针长度
        for (let i = 0; i < newList.length; i++) { // 环列表
          let ring = newList[i]// 每个环对象
          let sum = 0
          for (let n = 0; n < ring.length; n++) { // 相位累计长度
            // if (ring[n].mode !== 7) {
            sum = sum + ring[n].value + (ring[n].sum ? ring[n].sum : 0)
            if (j < sum) {
              let phaseId = ring[n].id
              currentIds = currentIds + '-' + phaseId
              break
            }
            // }
          }
          // for (let n = 0; n < ring.length; n++) { // 相位累计长度
          //   if (ring[n].mode !== 7) {
          //     sum = sum + ring[n].split
          //     if (j < sum) {
          //       let phaseId = ring[n].id
          //       currentIds = currentIds + '-' + phaseId
          //       break
          //     }
          //   }
          // }
        }
        if (lastCurrentIds !== currentIds && lastCurrentIds !== '') { // 当前相位id和上一个相比不同说明相位变化了
          phaseList.push(lastCurrentIds)
          this.stateList.push(j)// 阶段累计长度的集合
        }
        lastCurrentIds = currentIds
        currentIds = ''
      }
      let newPhaselist = []
      phaseList.forEach(i => {
        let rangeArr = i.split('-').map(Number)
        if (rangeArr.length > 2) {
          newPhaselist.push([
            JSON.parse(JSON.stringify(rangeArr[1])),
            JSON.parse(JSON.stringify(rangeArr[2]))
          ])
        } else {
          newPhaselist.push([
            JSON.parse(JSON.stringify(rangeArr[1]))
          ])
        }
      })
      for (let i = this.stateList.length - 1; i >= 1; i--) {
        this.narr.push(this.stateList[i] - this.stateList[i - 1])
      }
      this.narr.reverse()// 阶段差
      for (let i = 0; i < newPhaselist.length; i++) {
        let stage = JSON.parse(JSON.stringify(newPhaselist[i]))
        let newStage = []
        stage.map(item => {
          for (let ring of newList) {
            for (let ringItem of ring) {
              if (item === ringItem.id && (ringItem.mode !== 7 && ringItem.mode !== 8 && ringItem.mode !== 9)) {
                newStage.push(item)
              }
            }
          }
        })
        let stageItem = this.getStageItem(newStage, newList, i)
        overstagesList.push(JSON.parse(JSON.stringify(stageItem)))
      }
      this.overlapCycle = overstagesList.reduce((prev, curr) => prev + parseInt(curr.split), 0)
      this.stagesListOver = JSON.parse(JSON.stringify(overstagesList))
      console.log(this.stagesListOver)
    },
    getStageItem (stageArr, ringsList, i) {
      let res = {
        key: i,
        split: this.narr[i], // 阶段绿性比
        phases: stageArr,
        delaystart: 0,
        advanceend: 0
      }
      // let splitArr = []
      let delaystartArr = []
      let advanceendArr = []
      for (let rings of ringsList) {
        for (let ring of rings) {
          if (stageArr.includes(ring.id)) {
            // let split = ring.value
            let delaystart = ring.delaystart
            let advanceend = ring.advanceend
            // splitArr.push(split)
            delaystartArr.push(delaystart)
            advanceendArr.push(advanceend)
          }
        }
      }
      // splitArr.sort(function (a, b) { return a - b })
      delaystartArr.sort(function (a, b) { return b - a })
      advanceendArr.sort(function (a, b) { return a - b })
      // res.split = splitArr.length > 0 ? splitArr[0] : 0
      res.delaystart = delaystartArr.length > 0 ? delaystartArr[0] : 0
      res.advanceend = advanceendArr.length > 0 ? advanceendArr[0] : 0
      return res
    },
    checkStage (rings) {
      if (!rings.phase || !rings.rings) return
      let idPattern = this.allPatternList.filter(item => item.id === rings.patternid)
      if (idPattern.length === 0) return
      let ringList = this.allPatternList.filter(item => {
        return item.id === rings.patternid
      })[0].rings
      let filterPattern = []
      for (let i of ringList) {
        for (let j of this.controlData.rings) {
          let filterSequence = i.filter(item => j.sequence.includes(item.id))
          if (filterSequence.length > 0) {
            filterPattern.push(filterSequence)
          }
        }
      }
      // let mapAdd = rings.phase.map(item => {
      //   return {
      //     id: item.id,
      //     split: item.split
      //   }
      // })
      // let newRings = rings.rings.map(j => {
      //   return j.sequence
      // })
      // let newList = newRings.map(item => {
      //   let ret = []
      //   item.map(i => {
      //     const find = mapAdd.find(j => j.id === i)
      //     if (find) {
      //       ret.push(find)
      //     }
      //   })
      //   return ret
      // })
      // let mapAdds = newList.map(item => {
      //   return item.map(val => {
      //     return val.split
      //   })
      // })
      // let maxCycle = mapAdds.length > 0 ? mapAdds.map(item => {
      //   return item.length > 0 ? item.reduce((a, b) => {
      //     return a + b
      //   }) : 0
      // }) : 0
      let mapAdd = filterPattern.map(item => {
        return item.map(val => {
          return val.value + (val.sum ? val.sum : 0)
        })
      })
      let maxCycle = mapAdd.length > 0 ? mapAdd.map(item => {
        return item.length > 0 ? item.reduce((a, b) => {
          return a + b
        }) : 0
      }) : 0
      this.max = Math.max(...maxCycle)// 每个环的周期最大值
      this.getControl(filterPattern)
    },
    handleGetData (data) {
      let that = this
      if (data.name === '') {
        if (that.$i18n.locale === 'en') {
          data.name = 'Pattern' + data.patternid
        } else if (that.$i18n.locale === 'zh') {
          data.name = '方案' + data.patternid
        }
      }
      Object.keys(data).forEach(function (key) {
        if (that.$i18n.locale === 'en') {
          if (key === 'mode') {
            if (data[key] > 0 && data[key] < 6) {
              data[key] = that.ParamsModeEn.get(data[key])
            } else {
              data[key] = that.ParamsModeEn.get(0)
            }
          }
          // if (key === 'control') {
          //   data[key] = that.ParamsControlEn.get(data[key])
          // }
          if (key === 'phase' || key === 'overlap') {
            for (let val of data[key]) {
              val.typestr = that.phaseTypeEn.get(val.type)
              val.pedtypestr = that.phaseTypeEn.get(val.pedtype)
            }
          }
        } else if (that.$i18n.locale === 'zh') {
          if (key === 'mode') {
            if (data[key] > 0 && data[key] < 6) {
              data[key] = that.ParamsMode.get(data[key])
            } else {
              data[key] = that.ParamsMode.get(0)
            }
          }
          // if (key === 'control') {
          //   data[key] = that.ParamsControl.get(data[key])
          // }
          if (key === 'phase' || key === 'overlap') {
            for (let val of data[key]) {
              val.typestr = that.phaseType.get(val.type)
              val.pedtypestr = that.phaseType.get(val.pedtype)
            }
          }
        }
      })
      return data
    },
    reconnectionDev () {
      this.registerMessage()
    },
    queryDevParams () {
      queryDevice(this.AgentId).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        let devParams = res.data.data.jsonparam
        this.ip = devParams.ip
        this.port = String(devParams.port)
        this.protocol = res.data.data.protocol
        this.agentId = res.data.data.agentid
        if (res.data.data.name) {
          this.agentName = res.data.data.name
        }
        this.platform = res.data.data.platform
        let state = res.data.data.state
        if (state === 'UP') {
          this.stateName = this.$t('openatccomponents.overview.online')
        } else {
          this.stateName = this.$t('openatccomponents.overview.offline')
        }
        this.registerMessage() // 注册消息
        this.initData()
        // 配置工具没参数的时候
        this.getIntersectionInfo(this.agentId)
      })
    },
    getPhase () {
      uploadSingleTscParam('phase', this.agentId).then(data => {
        let res = data.data
        if (!res.success) {
          if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
            let success = data.data.data.content.success
            if (success !== 0) {
              let errormsg = 'openatccomponents.overview.putTscControlError' + success
              this.$message.error(this.$t(errormsg))
              return
            }
          }
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          return
        }
        if (res.data.data && res.data.data.phaseList) {
          this.phaseList = res.data.data.phaseList
        }
      })
    },
    getPlatform () {
      queryDevice(this.AgentId).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        let devParams = res.data.data.jsonparam
        this.ip = devParams.ip
        this.port = String(devParams.port)
        this.protocol = res.data.data.protocol
        this.agentId = res.data.data.agentid
        if (res.data.data.name) {
          this.agentName = res.data.data.name
        }
        this.platform = res.data.data.platform
        let func = 'allFunc'
        if (this.platform === 'OpenATC') {
          func = 'allFunc'
        }
        if (this.platform === 'SCATS' || this.platform === 'HUATONG') {
          func = 'basicFunc'
        }
        this.$store.dispatch('SaveFunctionLevel', func)
      })
    }
    // getChannelizationSetting (ChannelizationData) {
    //   // 路口已设置渠化，则总览默认显示渠化路口，未设置显示模版路口
    //   if (this.isfromatc === true) {
    //     this.$store.dispatch('SetShowHomePage', 'Graphical')
    //     this.$store.dispatch('isSetChannelization', false)
    //     if (ChannelizationData.data.success === true && JSON.stringify(ChannelizationData.data.data) !== '{}') {
    //       this.$store.dispatch('SetShowHomePage', 'Channelization')
    //       this.$store.dispatch('isSetChannelization', true)
    //     }
    //   }
    // },
  },
  destroyed () {
    this.isResend = false
    this.clearPatternInterval() // 清除定时器
    this.clearVolumeInterval()
    this.clearDetectorStatusTimer()
    this.clearRegisterMessageTimer() // 清除定时器
    this.getPlatform()
  }
}
</script>
